package com.leige.webconfig.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.foxinmy.weixin4j.model.WeixinAccount;
import com.foxinmy.weixin4j.mp.api.OauthApi;

/**
 * 登陆验证.
 * 
 * @author Administrator
 *
 */
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

	private final static Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

//	@Autowired
//	private OauthApi oauthApi;

	@Autowired
	private WeixinAccount weixinAccount;

	/**
	 * 验证用户的类型.
	 */
	private Integer permissionCode;

	/**
	 * 放行url的列表
	 */
	private List<String> passUrlList;

	/**
	 * html后缀的请求被重定向的地址,得确保此地址不会被拦截
	 */
	private String redirectUrl;

	public Integer getPermissionCode() {
		return permissionCode;
	}

	public void setPermissionCode(final Integer permissionCode) {
		this.permissionCode = permissionCode;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(final String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}

	public List<String> getPassUrlList() {
		return passUrlList;
	}

	public void setPassUrlList(final List<String> passUrlList) {
		this.passUrlList = passUrlList;
	}

	@Override
	public boolean preHandle(final HttpServletRequest request,final HttpServletResponse response, final Object handler) throws Exception {
		String uri = request.getRequestURI();
		String realredirectUrl;

		if (isMappingPassUrlList(uri) || isLogin(request))
			return true;
		
		realredirectUrl = getRealRedirectUrl(request, redirectUrl);
		if (uri.endsWith(".html")) {
			// 在放行列表中不存在并且没有登录
			response.sendRedirect(realredirectUrl);
			if (logger.isInfoEnabled()) {
				logger.info("用户未登录，程序将跳转至登陆页面:" + realredirectUrl);
			}
		} else {
			response.setContentType("application/json;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.sendError(500, "未登陆");
			response.flushBuffer();
			if (logger.isInfoEnabled()) logger.info("用户未登录，终止请求");
		}
		return false;
	}

	/**
	 * 是否能匹配上放行列表的url
	 * 
	 * @param address
	 * @return
	 */
	private boolean isMappingPassUrlList(final String address) {
		boolean flag = false;
		if (passUrlList != null) {
			for (String string : passUrlList) {
				if (address.matches(string)) {
					flag = true;
					break;
				}
			}
		}
		return flag;
	}


	/**
	 * 获取将要重定向的地址.
	 * 
	 * @param url
	 * @return
	 */
	private String getRealRedirectUrl(final HttpServletRequest request, final String url) {
		if (StringUtils.isEmpty(url)) {
			return buildWinxinAuthAddress(request);
		}
		// 如果重定向的地址为工程中的地址且不存在不拦截列表中，替换成拦截列表中第一个url.
		if (!url.startsWith("http") && !passUrlList.contains(url)) {
			return passUrlList.get(0);
		} else {
			return url;
		}
	}

	private String buildWinxinAuthAddress(final HttpServletRequest request) {
		String str;

		String authAddress = getredirectUri(request);
		// scope的范围有两种snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），snsapi_userinfo
		// （弹出授权页面，可通过openid拿到昵称、性别、所在地）
		str = new OauthApi(weixinAccount).getAuthorizeURL(weixinAccount.getId(), authAddress,"state", "snsapi_base");
		return str;
	}

	private String getredirectUri(final HttpServletRequest request) {
		String basePath = request.getScheme() + "://" + request.getServerName();
		int port = request.getServerPort();
		if (port != 80) {
			basePath = basePath + ":" + port;
		}
		String authAddress = basePath + "/auth/weixinLogin.html" + "?backUrl=" + request.getRequestURI();
		String queryString = request.getQueryString();
		if (queryString != null) {
			authAddress = authAddress + "?" + queryString;
		}
		return authAddress;
	}

	@Override
	public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}


	/**
	 * 判断用户是否已经登录.
	 * 
	 * @param request
	 * @return
	 */
	private boolean isLogin(final HttpServletRequest request) {
		boolean flag = true;
		return flag;
	}
}